//
//  IntegralExchangeViewController.m
//  CPICApp
//
//  Created by sinosoft on 13-3-12.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "IntegralExchangeViewController.h"
#import "IntegralExchangeTableViewCell.h"
#import "RCAlertViewUtil.h"
#import "NSString+SBJson.h"
#import "NSObject+SBJson.h"
#import "Config.h"
#import "UIImageView+WebCache.h"
#import "GiftDetailInfoViewController.h"
#import "ExchangeHistoryViewController.h"
#import "OperationLogView.h"
#import "AppDelegate.h"
#import <TencentOpenAPI/sdkdef.h>
#import <TencentOpenAPI/TencentOAuthObject.h>
#import "RCCaculateIntegral.h"

@interface IntegralExchangeViewController ()

@end

@implementation IntegralExchangeViewController
@synthesize txtCurrentIntegral,txtLockingIntegral;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
	// Do any additional setup after loading the view.
//    ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
//    ADD_LEFT_BUTTONITEM(@"back.png");
//    ADD_TITLE_NAMEITEM(@"积分兑换");
//    ADD_EXCHANGEHISTORY_BUTTONITEM(@"ExchangeHistory.png");
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        ADD_TITLE_NAMEITEM(@"积分兑换");
        ADD_EXCHANGEHISTORY_BUTTONITEM(@"ExchangeHistory.png");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        ADD_TITLE_NAMEITEM(@"积分兑换");
        ADD_EXCHANGEHISTORY_BUTTONITEM(@"ExchangeHistory.png");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        ADD_TITLE_NAMEITEM(@"积分兑换");
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, self.view.frame.size.height-44)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
        
        ADD_EXCHANGEHISTORY_BUTTONITEM(@"ExchangeHistory.png");
    }
    //self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    arrData=[[NSMutableArray alloc]init];
    IpageNo=1;
    ExchangeGiftId=[[NSString alloc]init];
    UIImageView *imgTopBackground=[[UIImageView alloc]initWithFrame:CGRectMake(0, 44, 640/2, 250/2)];
    imgTopBackground.image=[UIImage imageNamed:@"IntegralTop.png"];
    [self.view addSubview:imgTopBackground];
    [imgTopBackground release];
    
    UILabel *lblIntegral=[[UILabel alloc]initWithFrame:CGRectMake(92, 78, 93, 21)];
    lblIntegral.text=@"您当前的积分";
    lblIntegral.textColor=[UIColor blackColor];
    lblIntegral.font=[UIFont boldSystemFontOfSize:14.0];
    lblIntegral.backgroundColor=[UIColor clearColor];
    [self.view addSubview:lblIntegral];
    [lblIntegral release];
    
    txtCurrentIntegral=[[UITextField alloc]initWithFrame:CGRectMake(180, 78, 70, 31)];
    txtCurrentIntegral.borderStyle=UITextBorderStyleNone;
    txtCurrentIntegral.font=[UIFont boldSystemFontOfSize:17.0];
    txtCurrentIntegral.enabled=NO;
    [self.view addSubview:txtCurrentIntegral];
    
    UILabel *lblTag=[[UILabel alloc]initWithFrame:CGRectMake(247, 78, 42, 21)];
    lblTag.text=@"分";
    lblTag.textColor=[UIColor blackColor];
    lblTag.font=[UIFont boldSystemFontOfSize:14.0];
    lblTag.backgroundColor=[UIColor clearColor];
    [self.view addSubview:lblTag];
    [lblTag release];
    
    UIButton *btnExchange=[UIButton buttonWithType:UIButtonTypeCustom];
    btnExchange.frame=CGRectMake(265, 75, 87/2, 45/2);
    [btnExchange setImage:[UIImage imageNamed:@"Convert_Add.png"] forState:UIControlStateNormal];
    [btnExchange addTarget:self action:@selector(ExchangeBtnTap) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnExchange];
    
    
    UILabel *lblLockIntegral=[[UILabel alloc]initWithFrame:CGRectMake(92, 110, 159, 21)];
    lblLockIntegral.text=@"锁定的积分(兑换审批中)";
    lblLockIntegral.textColor=[UIColor blackColor];
    lblLockIntegral.font=[UIFont boldSystemFontOfSize:14.0];
    lblLockIntegral.backgroundColor=[UIColor clearColor];
    //[self.view addSubview:lblLockIntegral];
    [lblLockIntegral release];
    
    txtLockingIntegral=[[UITextField alloc]initWithFrame:CGRectMake(250, 110, 70, 31)];
    txtLockingIntegral.borderStyle=UITextBorderStyleNone;
    txtLockingIntegral.font=[UIFont boldSystemFontOfSize:17.0];
    txtLockingIntegral.enabled=NO;
    //[self.view addSubview:txtLockingIntegral];
    
    UILabel *lblTag1=[[UILabel alloc]initWithFrame:CGRectMake(295, 110, 42, 21)];
    lblTag1.text=@"分";
    lblTag1.textColor=[UIColor blackColor];
    lblTag1.font=[UIFont boldSystemFontOfSize:14.0];
    lblTag1.backgroundColor=[UIColor clearColor];
    //[self.view addSubview:lblTag1];
    [lblTag1 release];
    
    //添加UITableview
    TableViewExchange = [[UITableView alloc]initWithFrame:CGRectMake(-10, 160, 340, self.view.frame.size.height-153) style:UITableViewStyleGrouped];
	TableViewExchange.delegate = self;
	TableViewExchange.dataSource = self;
    
    TableViewExchange.opaque = NO;
    TableViewExchange.backgroundView = nil;
    TableViewExchange.autoresizingMask = UIViewContentModeTop;
    TableViewExchange.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    TableViewExchange.scrollEnabled=YES;
    TableViewExchange.backgroundColor=[UIColor clearColor];
    //[TableViewUser reloadData];
	[self.view addSubview:TableViewExchange];
    if (_refreshHeaderView == nil) {
		
		EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - TableViewExchange.bounds.size.height, self.view.frame.size.width, TableViewExchange.bounds.size.height)];
		view.delegate = self;
		[TableViewExchange addSubview:view];
		_refreshHeaderView = view;
		[view release];
    }
    //  update the last update date
	[_refreshHeaderView refreshLastUpdatedDate];
    [self setRequest];
    
    
    
    _permissions = [[NSArray arrayWithObjects:
                     kOPEN_PERMISSION_GET_USER_INFO,
                     kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                     kOPEN_PERMISSION_ADD_ALBUM,
                     kOPEN_PERMISSION_ADD_IDOL,
                     kOPEN_PERMISSION_ADD_ONE_BLOG,
                     kOPEN_PERMISSION_ADD_PIC_T,
                     kOPEN_PERMISSION_ADD_SHARE,
                     kOPEN_PERMISSION_ADD_TOPIC,
                     kOPEN_PERMISSION_CHECK_PAGE_FANS,
                     kOPEN_PERMISSION_DEL_IDOL,
                     kOPEN_PERMISSION_DEL_T,
                     kOPEN_PERMISSION_GET_FANSLIST,
                     kOPEN_PERMISSION_GET_IDOLLIST,
                     kOPEN_PERMISSION_GET_INFO,
                     kOPEN_PERMISSION_GET_OTHER_INFO,
                     kOPEN_PERMISSION_GET_REPOST_LIST,
                     kOPEN_PERMISSION_LIST_ALBUM,
                     kOPEN_PERMISSION_UPLOAD_PIC,
                     kOPEN_PERMISSION_GET_VIP_INFO,
                     kOPEN_PERMISSION_GET_VIP_RICH_INFO,
                     kOPEN_PERMISSION_GET_INTIMATE_FRIENDS_WEIBO,
                     kOPEN_PERMISSION_MATCH_NICK_TIPS_WEIBO,
                     nil] retain];
    //NSString *appid = @"100389997";
    NSString *appid = @"222222";
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:appid
											andDelegate:self];
    //SinaWeibo *sinaweibo = [self sinaweibo];
}
-(void) ClickCallOutBtn
{
    
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)ClickExchangeHistoryBtn
{
    ExchangeHistoryViewController *historyViewCtrl=[[ExchangeHistoryViewController alloc]init];
    [self.navigationController pushViewController:historyViewCtrl animated:YES];
    [historyViewCtrl release];
}
-(void)ExchangeBtnTap
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.bIntegralManagement=TRUE;
    int j=0;
    ExchangeIntegral=0;
    ExchangeNum=0;
    ExchangeGiftId=@"";
    for (int i=0; i<[arrData count]; i++)
    {
        
        //NSIndexPath *indexPath_1=[NSIndexPath indexPathForRow:i inSection:0];
        //IntegralExchangeTableViewCell *cell=(IntegralExchangeTableViewCell *)[TableViewExchange cellForRowAtIndexPath:indexPath_1];
        //NSString *strNum=cell.lblNum.text;
        NSString *strNum=[[NSString alloc]init];
         NSMutableDictionary *dictDataItem=[arrData objectAtIndex:i];
        if ([dictDataItem objectForKey:@"num"])
        {
            strNum=[dictDataItem objectForKey:@"num"];
        }
       
        NSInteger Num=strNum.intValue;
        if (Num>0)
        {
            j++;
            if (j>1)
            {
                [self justShowMessage:@"一次只能提交一种类型的礼品兑换" title:@"注意"];
                return;
            }
            ExchangeNum=Num;
            //ExchangeIntegral=Num*cell.lblGiftintegral.text.intValue;
            NSString *strIntegral=[dictDataItem objectForKey:@"giftintegral"];
            ExchangeIntegral=Num*strIntegral.intValue;
            ExchangeGiftId=[[arrData objectAtIndex:i]valueForKey:@"giftId"];
        }
        
    }
    if (j<1) {
        [self justShowMessage:@"请选择你要兑换的礼品" title:@"注意"];
        return;
    }
    if (ExchangeIntegral>self.txtCurrentIntegral.text.intValue) {
        [self justShowMessage:@"兑换礼品所需的积分已经超过你当前拥有的积分" title:@"注意"];
        return;
    }
    [self setExchangeRequest];
}

#pragma UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [arrData count];
}

- (CGFloat)tableView:(UITableView *)atableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 55;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *Identifier=@"Identifier";
    IntegralExchangeTableViewCell *cell=(IntegralExchangeTableViewCell *)[TableViewExchange dequeueReusableCellWithIdentifier:Identifier];
    if (cell==nil)
    {
        cell=[[[IntegralExchangeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier]autorelease];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        NSLog(@"************cellID  %d",indexPath.row);
    }
    NSMutableDictionary *dictDataItem=[arrData objectAtIndex:indexPath.row];
    cell.lblGiftName.text=[dictDataItem objectForKey:@"giftName"];
    cell.lblGiftintegral.text=[dictDataItem objectForKey:@"giftintegral"];
    if ([dictDataItem objectForKey:@"num"]) {
        cell.lblNum.text=[dictDataItem objectForKey:@"num"];
    }
    else
    {
        cell.lblNum.text=@"0";
    }
    cell.btnAdd.tag=indexPath.row;
    cell.btnReduce.tag=indexPath.row;
    giftId=[dictDataItem objectForKey:@"giftId"];
    giftName=[dictDataItem objectForKey:@"giftName"];
    giftintegral=[dictDataItem objectForKey:@"giftintegral"];
    [cell.btnAdd addTarget:self action:@selector(addGiftNum:) forControlEvents:UIControlEventTouchDown];
    [cell.btnReduce addTarget:self action:@selector(reduceGiftNum:) forControlEvents:UIControlEventTouchDown];
    
	return cell;
}
-(void)addGiftNum:(id)sender
{
    UIButton *btn=(UIButton *)sender;
    NSInteger indexId=btn.tag;
    
    
    NSIndexPath *indexPath_1=[NSIndexPath indexPathForRow:indexId inSection:0];
    NSArray *indexArray=[NSArray arrayWithObject:indexPath_1];
    IntegralExchangeTableViewCell *cell=(IntegralExchangeTableViewCell *)[TableViewExchange cellForRowAtIndexPath:indexPath_1];
    NSString *strNum=cell.lblNum.text;
    NSInteger Num=strNum.intValue;
    Num=Num+1;
    NSString *strNum1=[NSString stringWithFormat:@"%d",Num];
    
    NSMutableDictionary *dictDataItem=[arrData objectAtIndex:indexId];
    [dictDataItem setValue:strNum1 forKey:@"num"];
    [arrData replaceObjectAtIndex:indexId withObject:dictDataItem];
    
    //[cell.lblNum setText:strNum1];
    [TableViewExchange reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationNone];
}
-(void)reduceGiftNum:(id)sender
{
    UIButton *btn=(UIButton *)sender;
    NSInteger indexId=btn.tag;
    
    NSIndexPath *indexPath_1=[NSIndexPath indexPathForRow:indexId inSection:0];
    NSArray *indexArray=[NSArray arrayWithObject:indexPath_1];
    IntegralExchangeTableViewCell *cell=(IntegralExchangeTableViewCell *)[TableViewExchange cellForRowAtIndexPath:indexPath_1];
    NSString *strNum=cell.lblNum.text;
    NSInteger Num=strNum.intValue;
    if (Num>0) {
        Num=Num-1;
    }
    NSMutableDictionary *dictDataItem=[arrData objectAtIndex:indexId];
    NSString *strNum1=[NSString stringWithFormat:@"%d",Num];
    [dictDataItem setValue:strNum1 forKey:@"num"];
    [arrData replaceObjectAtIndex:indexId withObject:dictDataItem];
    //[cell.lblNum setText:strNum1];
    [TableViewExchange reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationNone];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *dictDataItem=[arrData objectAtIndex:indexPath.row];
    GiftDetailInfoViewController *giftDetailInfoViewCtrl=[[GiftDetailInfoViewController alloc]init];
    giftDetailInfoViewCtrl.strGiftId=[dictDataItem objectForKey:@"giftId"];
    [self.navigationController pushViewController:giftDetailInfoViewCtrl animated:YES];
    [giftDetailInfoViewCtrl release];
}


-(void)setRequest//向太保移动平台发送请求报文
{
    NSLog(@"userinfodefault%@",[[NSUserDefaults standardUserDefaults] objectForKey:DICT_USER_INFO]);
    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    if (dictUserInfo!=nil) {
        if ([dictUserInfo valueForKey:@"UserAccount"]) {
            NSLog(@"%@",[dictUserInfo valueForKey:@"UserAccount"]);
        }
    }
    else
    {
        [self justShowMessage:@"用户还没登录,请登录系统" title:@"注意"];
        return;
    }
    
//    NSString *strRequestCode=@"RequestCode=31201";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    NSNumber *pageNo=[NSNumber numberWithInt:IpageNo];
    NSNumber *pageSize=[NSNumber numberWithInt:10];
    [dicRequest setObject:pageNo forKey:@"pageNo"];
    [dicRequest setObject:pageSize forKey:@"pageSize"];
    [dicRequest setObject:[dictUserInfo valueForKey:@"UserAccount"] forKey:@"userAccount"];
    NSString *strRequestJson=[dicRequest JSONRepresentation];
//    strRequestJson=[NSString stringWithFormat:@"&RequestData=%@",strRequestJson];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestJson];
//    NSString *strUrlEncod = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    NSURL *myurl = [NSURL URLWithString:strUrlEncod];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"请求报文为:%@",strUrl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"31201" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseFail:)];
    [request setDidFinishSelector:@selector(ResonseSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) {
        NSLog(@"88888");
        //[NSThread sleepForTimeInterval:1];
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictGiftList=[dictResponse objectForKey:@"giftList"];
    //arrData=[dictGiftList objectForKey:@"data"];

    NSMutableArray *myArrData=[dictGiftList valueForKey:@"data"];
    for (int i=0; i<[myArrData count]; i++) {
        NSMutableDictionary *dictItem=[myArrData objectAtIndex:i];
        [arrData addObject:dictItem];
    }
    [TableViewExchange reloadData];
    
    NSString *Code =@"31401";
    OperationLogView *operationlog =[[OperationLogView alloc]initView:Code withtype:@"1" withserialno:@""];
    [operationlog setOperationLogRequest];
    [operationlog setHidden:YES];
    [self.view addSubview:operationlog];
    [operationlog release];
}

- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}

-(void)setExchangeRequest//向太保移动平台发送请求报文
{
    NSLog(@"userinfodefault%@",[[NSUserDefaults standardUserDefaults] objectForKey:DICT_USER_INFO]);
    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    if (dictUserInfo!=nil) {
        if ([dictUserInfo valueForKey:@"UserAccount"]) {
            NSLog(@"%@",[dictUserInfo valueForKey:@"UserAccount"]);
        }
    }
    else
    {
        [self justShowMessage:@"用户还没登录,请登录系统" title:@"注意"];
        return;
    }
    
    
//    NSString *strRequestCode=@"RequestCode=31401";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    if (ExchangeGiftId.length!=0) {
        [dicRequest setObject:ExchangeGiftId forKey:@"giftId"];
    }
    else
    {
        [dicRequest setObject:@"" forKey:@"giftId"];
    }
    NSString *strGiftNum=[[NSString alloc]initWithFormat:@"%d",ExchangeNum];
    if (strGiftNum.length!=0) {
        [dicRequest setObject:strGiftNum forKey:@"giftNum"];
    }
    else
    {
        [dicRequest setObject:@"" forKey:@"giftNum"];
    }
    
    NSString *strGiftTotalintegral=[[NSString alloc]initWithFormat:@"%d",ExchangeIntegral];
    if (strGiftTotalintegral.length!=0) {
        [dicRequest setObject:strGiftTotalintegral forKey:@"giftTotalintegral"];
    }
    else
    {
        [dicRequest setObject:@"" forKey:@"giftTotalintegral"];
    }
    [dicRequest setObject:[dictUserInfo valueForKey:@"UserAccount"] forKey:@"userAccount"];
    NSString *strRequestJson=[dicRequest JSONRepresentation];
//    strRequestJson=[NSString stringWithFormat:@"&RequestData=%@",strRequestJson];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestJson];
//    NSString *strUrlEncod = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    NSURL *myurl = [NSURL URLWithString:strUrlEncod];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"请求报文为:%@",strUrl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"31401" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseExchangeFail:)];
    [request setDidFinishSelector:@selector(ResponseExchangeSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) {
        NSLog(@"88888");
        // [NSThread sleepForTimeInterval:1];
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResponseExchangeSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictHead=[dictResponse valueForKey:@"head"];
    NSString *strResult= [[NSString alloc] initWithFormat:@"%@",[dictHead objectForKey:@"success"]];
    NSLog(@"strResult%@",strResult);
    if ([strResult isEqualToString:@"1"]) {
        //[self justShowMessage:@"兑换成功" title:nil];
        UIAlertView *myalert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"兑换成功" delegate:self cancelButtonTitle:@"取消分享" otherButtonTitles:@"分享到新浪微博",@"分享到腾讯微博", nil];
        myalert.tag=1;
        [myalert show];
        [myalert release];
        
        txtCurrentIntegral.text=[dictResponse valueForKey:@"currentIntegral"];
        
        NSString *Code =@"30401";
        NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
        NSString * serialNostr=[accountDefaults objectForKey:@"OPERATIONLOG"];
        OperationLogView *operationlog =[[OperationLogView alloc]initView:Code withtype:@"2" withserialno:serialNostr];
        [operationlog setOperationLogRequest];
        [operationlog setHidden:YES];
        [self.view addSubview:operationlog];
        [operationlog release];
    }
    else
    {
        NSString *strError=[dictHead valueForKey:@"message"];
        [self justShowMessage:strError title:nil];
    }
    [strResult release];
    
}

- (void)ResponseExchangeFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==1) {
        if (buttonIndex==0) {
        }
        else if(buttonIndex==1)
        {
            strShareContent=@"积分兑换信息分享积分兑换信息分享积分兑换信息分享积分兑换信息分享积分兑换信息分享";
            isContent=YES;
            isImage=NO;
            [self shareSina];
        }
        else if(buttonIndex==2)
        {
            strShareContent=@"积分兑换信息分享积分兑换信息分享积分兑换信息分享积分兑换信息分享积分兑换信息分享";
            isContent=YES;
            isImage=NO;
            [self shareQQ];
        }
        else
        {
        }
    }
}

-(void)caculateShareIntegral
{
    RCCaculateIntegral *rcCaculateIntegral=[[RCCaculateIntegral alloc]initCaculateIntegalView];
    [rcCaculateIntegral setCaculatRequest:@"61002"];
    [rcCaculateIntegral setHidden:YES];
    [self.view addSubview:rcCaculateIntegral];
    [rcCaculateIntegral release];
}
#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:TableViewExchange];
	
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
	[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];
    IpageNo=IpageNo+1;
    [self setRequest];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}







static int post_image_status_times = 0;
static int post_status_times = 0;
-(void)shareSina
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.bKnowledgeInsurance=TRUE;
    
    AppDelegate *appMyDelegate=[[UIApplication sharedApplication]delegate];
    appMyDelegate.iLoginorAccountTag=1;
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    NSLog(@"%@", [keyWindow subviews]);
    
    
    SinaWeibo *sinaweibo = [self sinaweibo];
    
    if ([sinaweibo isAuthValid]) {
        //[self justShowMessage:@"你已经授权新浪微博" title:@"提示"];
        if (isImage==YES && isContent==NO) {
            if (!postImageStatusText)
            {
                post_image_status_times ++;
                [postImageStatusText release], postImageStatusText = nil;
                postImageStatusText = [[NSString alloc] initWithFormat:@"CPICApp image status : %i %@", post_image_status_times, [NSDate date]];
            }
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                message:[NSString stringWithFormat:@"你将分享以上内容到新浪微博 \"%@\"", postImageStatusText]
                                                               delegate:self cancelButtonTitle:@"Cancel"
                                                      otherButtonTitles:@"OK", nil];
            alertView.tag = 1;
            [alertView show];
            [alertView release];
        }
        else if(isImage==NO && isContent==YES)
        {
            if (!postStatusText)
            {
                post_status_times ++;
                [postStatusText release], postStatusText = nil;
                postStatusText = [[NSString alloc] initWithFormat:@"CPICApp text status : %i %@%@", post_status_times, [NSDate date],strShareContent];
            }
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                                message:[NSString stringWithFormat:@"你将分享以上内容到新浪微博 \"%@\"", postStatusText]
                                                               delegate:self cancelButtonTitle:@"Cancel"
                                                      otherButtonTitles:@"OK", nil];
            alertView.tag = 0;
            [alertView show];
            [alertView release];
        }
        
    }
    else
    {
        [sinaweibo logIn];
    }
    
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        if (alertView.tag == 0)
        {
            // post status
            NSLog(@"保险知识%@",postStatusText);
            SinaWeibo *sinaweibo = [self sinaweibo];
            [sinaweibo requestWithURL:@"statuses/update.json"
                               params:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       postStatusText, @"status",
                                       nil]
                           httpMethod:@"POST"
                             delegate:self];
            
        }
        else if (alertView.tag == 1)
        {
            // post image status
            
            SinaWeibo *sinaweibo = [self sinaweibo];
            
            [sinaweibo requestWithURL:@"statuses/upload.json"
                               params:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       postImageStatusText, @"status",
                                       imageDown, @"pic", nil]
                           httpMethod:@"POST"
                             delegate:self];
            
        }
        else if(alertView.tag==2)
        {
            if (isImage==YES && isContent==NO) {
                TCAddShareDic *params = [TCAddShareDic dictionary];
                params.paramTitle = @"太平洋保险-积分兑换信息分享";
                params.paramComment = strInsuranceTitle;
                //            params.paramSummary =  @"中国太平洋保险成立于1991年5月13日，总部设在上海，成功在A股和H股上市，旗下拥有太平洋寿险、太平洋产险、太平洋资产管理公司和长江养老保险等专业子公司，保持持续领先的市场地位。";
                //            params.paramImages = @"http://img1.gtimg.com/tech/pics/hv1/95/153/847/55115285.jpg";
                
                if ([ImgUrl isKindOfClass:[NSString class]]==YES) {
                    if (ImgUrl.length!=0) {
                        params.paramImages=ImgUrl;
                    }
                }
                else
                {
                    [self justShowMessage:@"图片地址无效" title:@"注意"];
                }
                
                params.paramUrl = @"http://www.cpic.com.cn/cpic/index.shtml";
                
                if(![_tencentOAuth addShareWithParams:params]){
                    [self showInvalidTokenOrOpenIDMessage];
                }
            }
            
            if (isContent==YES && isImage==NO) {
                TCAddShareDic *params = [TCAddShareDic dictionary];
                params.paramTitle = @"太平洋保险-积分兑换信息分享";
                params.paramComment = strInsuranceTitle;
                params.paramSummary = strShareContent;
                //            params.paramImages = @"http://img1.gtimg.com/tech/pics/hv1/95/153/847/55115285.jpg";
                
                params.paramUrl = @"http://www.cpic.com.cn/cpic/index.shtml";
                
                if(![_tencentOAuth addShareWithParams:params]){
                    [self showInvalidTokenOrOpenIDMessage];
                }
            }
            
        }
        else if(alertView.tag==3)
        {
            TCAddShareDic *params = [TCAddShareDic dictionary];
            params.paramTitle = @"太平洋保险-积分兑换信息分享";
            params.paramComment = strInsuranceTitle;
            params.paramSummary = strShareContent;
            //            params.paramImages = @"http://img1.gtimg.com/tech/pics/hv1/95/153/847/55115285.jpg";
            
            params.paramUrl = @"http://www.cpic.com.cn/cpic/index.shtml";
            
            if(![_tencentOAuth addShareWithParams:params]){
                [self showInvalidTokenOrOpenIDMessage];
            }
        }
    }
}
- (void)showInvalidTokenOrOpenIDMessage{
    UIAlertView *alert = [[[UIAlertView alloc]initWithTitle:@"api调用失败" message:@"可能授权已过期，请重新获取" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] autorelease];
    [alert show];
}
/**
 * Called when the add_share has response.
 */
- (void)addShareResponse:(APIResponse*) response {
	if (response.retCode == URLREQUEST_SUCCEED)
	{
		
		[self  caculateShareIntegral];
		NSMutableString *str=[NSMutableString stringWithFormat:@""];
		for (id key in response.jsonResponse) {
			[str appendString: [NSString stringWithFormat:@"%@:%@\n",key,[response.jsonResponse objectForKey:key]]];
		}
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作成功" message:nil
							  
													   delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles:nil];
		[alert show];
        [alert release];
		
		
		
	}
	else {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作失败" message:[NSString stringWithFormat:@"%@", response.errorMsg]
							  
													   delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles: nil];
		[alert show];
        [alert release];
	}
}

-(void)shareQQ
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.bKnowledgeInsurance=TRUE;
    
    if([_tencentOAuth isSessionValid])
    {
        if (isImage==YES && isContent==NO) {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"你将分享以上内容到腾讯微博" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag=2;
            [alert show];
            [alert release];
        }
        else if(isContent==YES && isImage==NO)
        {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"你将分享以上内容到腾讯微博" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag=3;
            [alert show];
            [alert release];
        }
        
    }
    else
    {
        [_tencentOAuth authorize:_permissions inSafari:NO];
    }
    
}

-(void)setBindCheckRequest//向太保移动平台发送请求报文
{
    //    NSString *strRequestCode=@"RequestCode=62102";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    if (QQopenId.length!=0) {
        [dicRequest setValue:QQopenId forKey:@"UserId"];
    }
    else
    {
        [dicRequest setValue:@"" forKey:@"UserId"];
    }
    [dicRequest setValue:@"2" forKey:@"bindingType"];
    NSString *strRequestJson=[dicRequest JSONRepresentation];
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"62102" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseBindCheckFail:)];
    [request setDidFinishSelector:@selector(ResonseBindCheckSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) {
        NSLog(@"88888");
        // [NSThread sleepForTimeInterval:1];
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseBindCheckSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictHead=[dictResponse valueForKey:@"head"];
    NSString *strResult= [[NSString alloc] initWithFormat:@"%@",[dictHead objectForKey:@"success"]];
    NSLog(@"strResult%@",strResult);
    NSString *strUserAccount1=[dictResponse objectForKey:@"userAccount"];
    // if ([strResult isEqualToString:@"1"]) {
    if (strUserAccount1.length!=0) {
        //[self justShowMessage:@"登录成功" title:nil];
        bindingQQ=YES;
        [self checkQQAuth];
    }
    else
    {
        //[self justShowMessage:@"登录失败" title:nil];
        bindingQQ=NO;
        [self checkQQAuth];
        
    }
    
}
-(void)checkQQAuth
{
    if([_tencentOAuth isSessionValid])
    {
        if (bindingQQ==NO) {
            [self justShowMessage:@"你还没绑定本系统账户,请到绑定页面进行绑定" title:@"确定"];
        }
//        else
//        {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"你将分享以上内容到腾讯微博" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag=2;
            [alert show];
            [alert release];
//        }
    }
    else
    {
        [_tencentOAuth authorize:_permissions inSafari:NO];
    }
    
    
}

- (void)ResponseBindCheckFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}


- (SinaWeibo *)sinaweibo
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return delegate.sinaweibo;
}
- (void)storeAuthData
{
    SinaWeibo *sinaweibo = [self sinaweibo];
    
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self justShowMessage:@"授权成功" title:nil];
}
#pragma mark - SinaWeibo Delegate

- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogIn userID = %@ accesstoken = %@ expirationDate = %@ refresh_token = %@", sinaweibo.userID, sinaweibo.accessToken, sinaweibo.expirationDate,sinaweibo.refreshToken);
    [self storeAuthData];
}

- (void)sinaweiboDidLogOut:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogOut");
    
}

- (void)sinaweiboLogInDidCancel:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboLogInDidCancel");
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo logInDidFailWithError:(NSError *)error
{
    NSLog(@"sinaweibo logInDidFailWithError %@", error);
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo accessTokenInvalidOrExpired:(NSError *)error
{
    NSLog(@"sinaweiboAccessTokenInvalidOrExpired %@", error);
    
}

#pragma mark - SinaWeiboRequest Delegate

- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error
{
    if ([request.url hasSuffix:@"users/show.json"])
    {
        [userInfo release], userInfo = nil;
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
        [statuses release], statuses = nil;
    }
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post status \"%@\" failed!", postStatusText]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        NSLog(@"Post status failed with error : %@", error);
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post image status \"%@\" failed!", postImageStatusText]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        NSLog(@"Post image status failed with error : %@", error);
    }
    
    
    
}

- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result
{
    [self caculateShareIntegral];
    if ([request.url hasSuffix:@"users/show.json"])
    {
        [userInfo release];
        userInfo = [result retain];
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
        [statuses release];
        statuses = [[result objectForKey:@"statuses"] retain];
    }
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:@"分享成功"
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        [postStatusText release], postStatusText = nil;
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
//                                                            message:[NSString stringWithFormat:@"Post image status \"%@\" succeed!", [result objectForKey:@"text"]]
//                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:@"分享成功"
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        [postImageStatusText release], postImageStatusText = nil;
    }
    
}
- (void)storeAuthQQ
{
    
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              QQAccessToken, @"QQAccessToken",
                              QQopenId, @"QQopenId", nil];
    
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"Dict_QQAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
#pragma mark - TencentSessionDelegate
/**
 * Called when the user successfully logged in.
 */
- (void)tencentDidLogin {
	// 登录成功
	[self justShowMessage:@"QQ登录成功" title:nil];
    
    
    if (_tencentOAuth.accessToken
        && 0 != [_tencentOAuth.accessToken length])
    {
        QQAccessToken = _tencentOAuth.accessToken;
        QQopenId=_tencentOAuth.openId;
        [self storeAuthQQ];
        [self setBindCheckRequest];
    }
    else
    {
        QQAccessToken = @"登录不成功 没有获取accesstoken";
    }
    
}

/**
 * Called when the user dismissed the dialog without logging in.
 */
- (void)tencentDidNotLogin:(BOOL)cancelled
{
	if (cancelled){
        [self justShowMessage:@"用户取消登录" title:nil];
	}
	else {
        [self justShowMessage:@"登录失败" title:nil];
	}
	
}
/**
 * Called when the notNewWork.
 */
-(void)tencentDidNotNetWork
{
    [self justShowMessage:@"无网络连接，请设置网络" title:nil];
}

/**
 * Called when the logout.
 */
-(void)tencentDidLogout
{
    [self justShowMessage:@"退出登录成功，请重新登录" title:nil];
    QQAccessToken = @"";
    
    
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)dealloc
{
    [arrData release];
    [txtCurrentIntegral release];
    [txtLockingIntegral release];
    [super dealloc];
}

@end
